var express = require('express');
var router = express.Router();
var mongo = require("./db");

var mongodb = require("mongodb");
var ObjectId = mongodb.ObjectId;
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
// 添加商品接口
router.post("/add", function (req, res) {
  var obj = {
    id: +new Date(),
    imgsrc: req.body.imgsrc,
    pname: req.body.pname,
    price: req.body.price,
    se: req.body.se
  }
  mongo("insert", "prolist", obj, function () {
    res.send({ success: "添加接口" })
  })
})
// 查询商品列表
router.post("/getlist", function (req, res) {
  // 查询所有 {}
  // s1 s2 s3 
  var obj = {}
  if (req.body.se) { //分类
    obj.se = req.body.se;
  }
  if (req.body.pname) {//名称查询
    obj.pname = req.body.pname
  }
  if (req.body.price) {//价格查询
    obj.price = req.body.price
  }
  mongo("find", "prolist", obj, function (data) {
    res.send(data)
  })

})

// 删除接口
router.post("/del", function (req, res) {
  mongo("del", "prolist", { _id: ObjectId(req.body._id) }, function () {
    res.send({ success: "删除成功" })
  })
})
// 修改接口
router.post("/update", function (req, res) {
  var obj = {
    imgsrc: req.body.imgsrc,
    pname: req.body.pname,
    price: req.body.price,
    se: req.body.se
  }
  mongo("update", "prolist", [{ _id: ObjectId(req.body._id) }, obj], function () {
    res.send({ success: "修改成功" })
  })
})
// 添加购物车 
router.post("/addcart", function (req, res) {
  var obj = {
    id: +new Date(),
    imgsrc: req.body.imgsrc,
    pname: req.body.pname,
    price: req.body.price,
    se: req.body.se,
    num: 1
  }
  mongo("insert", "cartlist", obj, function () {
    res.send({ success: "添加成功" })
  })
})
// 查询购物车列表
router.post("/getcart", function (req, res) {
  mongo("find", "cartlist", {}, function (data) {
    res.send(data)
  })
})
// 数量更新
router.post("/updateNum", function (req, res) {
  mongo("update", "cartlist", [{ _id: ObjectId(req.body._id) }, { num: req.body.num }], function () {
    res.send({ success: "修改成功" })
  })
})

module.exports = router;
